package com.grape.juc.safe.sync;

/**
 * 描述:多线程抢购火车票
 * @author: myx
 * @date: 2019-05-05
 * Copyright © 2019-grape. All rights reserved.
 */
public class TrainTest implements Runnable{
    private static int trainCount = 100;
    @Override
    public void run() {
        while (trainCount > 0) {
            try {
                Thread.sleep(50);
            } catch (Exception e) {

            }
            sale4();
        }
    }

    /**
     * 购票操作
     */
    public void sale() {
        if (trainCount > 0) {
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
            trainCount--;
        }
    }

    /**
     * 同步代码块
     */
    public void sale1() {
        synchronized (this) {
            if (trainCount > 0) {
                System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
                trainCount--;
            }
        }
    }

    /**
     * 同步方法
     */
    public synchronized void sale2() {
        if (trainCount > 0) {
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
            trainCount--;
        }
    }

    /**
     * 静态同步函数
     */
    public static void sale3() {
        synchronized (TrainTest.class) {
            if (trainCount > 0) {
                System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
                trainCount--;
            }
        }
    }

    /**
     * 静态同步函数
     */
    public static synchronized void sale4() {
        if (trainCount > 0) {
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
            trainCount--;
        }
    }

    /**
     * 模拟线程安全问题
     * @param args
     */
    public static void main(String[] args) {
        TrainTest threadTrain = new TrainTest();
        Thread t1 = new Thread(threadTrain, "①号");
        Thread t2 = new Thread(threadTrain, "②号");
        t1.start();
        t2.start();
    }
}
